package ldh.fx.adminfx.controller;

import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Pos;
import javafx.scene.control.ContextMenu;
import javafx.scene.control.MenuItem;
import ldh.fx.adminfx.commpont.grid.GridTable;
import ldh.fx.adminfx.commpont.grid.PageResult;
import ldh.fx.adminfx.commpont.grid.Pageable;
import ldh.fx.adminfx.commpont.grid.Pagination;
import ldh.fx.adminfx.pojo.User;
import ldh.fx.adminfx.util.TableViewUtil;

import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.ResourceBundle;

public class Table2PageController implements Initializable {

    @FXML private GridTable<User> gridTable;

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        gridTable.setPageSizes(Arrays.asList(10, 20, 30, 50, 100));
        gridTable.setDefaultPageSize(10);
        gridTable.setLoadFunction(pageable -> {
            PageResult<User> userPageResult = loadUserDatas(pageable);
            return userPageResult;
        });

        gridTable.load(new Pagination(1, 10));
        TableViewUtil.alignment(Pos.CENTER, gridTable.getTableView());

        gridTable.getTableView().getColumns().forEach(c->{
            ContextMenu contextMenu = new ContextMenu();
            contextMenu.setUserData(c.getText());
            MenuItem menuItem = new MenuItem("冻结");
            menuItem.setOnAction(e->{
                System.out.print(c.getText());
            });
            contextMenu.getItems().addAll(menuItem);
            c.setContextMenu(contextMenu);
        });
    }

    private PageResult<User> loadUserDatas(Pageable pageable) {
        List<User> userList = new ArrayList();
        for(int i=0; i<pageable.getPageSize(); i++) {
            User user = new User();
            user.setId(i + (pageable.getPageNo() -1) * pageable.getPageSize());
            user.setName("name " + user.getId());
            user.setAge((int)(Math.random() * 100));
            user.setSex(user.getAge()%2);
            userList.add(user);
        }
        Double sleep = 3000 * Math.random();
        try {
            Thread.sleep(sleep.longValue());
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        PageResult<User> pageResult = new PageResult<>(pageable, 120, userList);
        return pageResult;
    }
}
